import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class CustomRuleHistoryPage extends StatefulWidget {
  const CustomRuleHistoryPage({super.key});

  @override
  State<CustomRuleHistoryPage> createState() => _CustomRuleHistoryPageState();
}

class _CustomRuleHistoryPageState extends State<CustomRuleHistoryPage> {
  late var barcode = TextEditingController();
  late var barcodeTemp = "";
  late var baseUrl = "";
  late var station = "";

  late List<Map<String, dynamic>> inputFields = [];
  // 初始化本地设置
  Future<void> initLocal() async {
    final prefs = await SharedPreferences.getInstance();
    var ip1 = prefs.getString("ip") ?? "";
    var port1 = prefs.getString("port") ?? "";
    var station1 = prefs.getString("station") ?? "";
    baseUrl = "http://$ip1:$port1";
    station = station1;
    barcode = TextEditingController(text: "");
    getData();
  }

  // 正确的方法定义
  Future<void> getData() async {
    try {
      final response = await http.get(
        Uri.parse(
          "$baseUrl/api/custRuleData/getCustRuleDatas?location=$station",
        ),
      );
      if (response.statusCode == 200) {
        // 处理成功响应
        final result = json.decode(response.body)["result"];
        for (var item in result) {
          Map<String, dynamic> temp = {};
          inputFields.add(item);
        }
        setState(() {});
      } else {
        // 处理错误
        print("请求失败: ${response.statusCode}");
      }
    } catch (e) {
      print("请求异常: $e");
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initLocal();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SizedBox(height: 10),
          Row(
            children: [
              Expanded(
                child: KeyboardListener(
                  focusNode: FocusNode(),
                  onKeyEvent: (e) async {
                    try {
                      if (e.character != null) {
                        barcodeTemp += e.character!;
                        barcode.text = "";
                      }
                      if (e.logicalKey == LogicalKeyboardKey.enter &&
                          barcodeTemp.isNotEmpty) {
                        barcode.text = barcodeTemp.replaceAll("\n", "");
                        barcodeTemp = "";

                        final response = await http.get(
                          Uri.parse(
                            "$baseUrl/api/custRuleData/getCustRuleDatas?location=$station&barcode=${barcode.text.replaceAll("\n", "")}",
                          ),
                        );
                        if (response.statusCode == 200) {
                          // 处理成功响应
                          print("object 返回成功;额");
                          final result = json.decode(response.body)["result"];
                          print(result);
                          for (var item in result) {
                            Map<String, dynamic> temp = {};
                            inputFields.add(item);
                          }
                          if (result.length == 0) {
                            inputFields.clear();
                          }
                          setState(() {
                          });
                        } else {
                          // 处理错误
                          print("请求失败: ${response.statusCode}");
                        }
                      }
                    } catch (e) {
                      print(e.toString());
                    }
                  },
                  child: TextField(
                    controller: barcode,
                    keyboardType: TextInputType.none,
                    onEditingComplete: () {},
                    readOnly: true,
                    textInputAction: TextInputAction.none, // 阻止默认的键盘动作
                    decoration: InputDecoration(
                      suffixIcon: barcode != ""
                          ? IconButton(
                        onPressed: () {
                          for (int i = 0; i < inputFields.length; i++) {
                            inputFields[i]["value"].clear();
                          }
                          barcode.clear();
                        },
                        icon: Icon(Icons.clear),
                      )
                          : null,
                      labelText: "产品条码",
                      border: OutlineInputBorder(),
                      labelStyle: TextStyle(
                        fontSize: 20, // 标签字体调小
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 25, // 关键：垂直内边距归零
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          // 使用 Expanded 包裹 TDTable，使其占据剩余高度
          TDTable(
            stripe: true,
            rowHeight: 60,
            height: 360,
            columns: [
              TDTableCol(title: "条码", colKey: "barcode"),
              TDTableCol(title: "方案", colKey: "planName"),
              TDTableCol(title: "工位", colKey: "location"),
              TDTableCol(
                title: "数据",
                colKey: "",
                cellBuilder: (BuildContext context, int index) {
                  return Row(
                    children: [
                      TDButton(
                        text: "查看",
                        theme: TDButtonTheme.primary,
                        onTap: () {
                          Navigator.of(context).push(
                            TDSlidePopupRoute(
                              modalBarrierColor: TDTheme.of(
                                context,
                              ).fontGyColor2,
                              slideTransitionFrom: SlideTransitionFrom.center,
                              builder: (context) {
                                Map<String, dynamic> i = json.decode(
                                  inputFields[index]["data"],
                                );

                                final allData = i.values
                                    .expand((list) => list)
                                    .toList();

                                // 2. 筛选 location == station 的数据
                                final filteredData = allData.where((item) {
                                  return item['location'] ==
                                      station; // 只保留 location 匹配 station 的项
                                }).toList();
                                return Padding(
                                  padding: EdgeInsets.all(50),
                                  child: TDTable(
                                    width: 750,
                                    stripe: true,
                                    height: 360,
                                    columns: [
                                      TDTableCol(title: '规则名称', colKey: 'name'),
                                      TDTableCol(
                                        title: '规则内容',
                                        colKey: 'ruleContent',
                                      ),
                                      TDTableCol(
                                        title: '规则长度',
                                        colKey: 'ruleLength',
                                      ),
                                      TDTableCol(
                                        title: '工位',
                                        colKey: 'location',
                                      ),
                                      TDTableCol(title: '值', colKey: 'value'),
                                    ],
                                    data: filteredData,
                                  ),
                                );
                              },
                            ),
                          );
                        },
                      ),
                    ],
                  );
                },
              ),
            ],
            data: inputFields,
          ),
        ],
      ),
    );
  }
}
